﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Commerce.Common;
using umbraco.cms.businesslogic.member;

namespace CommerceForUmbraco.adminSection.commerce
{
    public partial class orderDetailsCSV : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int filter = int.Parse(Request["f"]);
            DateTime startDateParam = DateTime.Parse(Request["sd"]);
            DateTime endDateParam = DateTime.Parse(Request["ed"]);

            // get collection values
            Commerce.Common.OrderCollection orders = null;

            //Assemble start and end dates.

            DateTime startDate;
            DateTime endDate = DateTime.Now;


            int year = DateTime.Today.Year;
            int month = DateTime.Today.Month;
            int day = DateTime.Today.Day;


            switch (filter)
            {
                case 1: // Yesterday
                    startDate = new DateTime(year, month, day).AddDays(-1);
                    endDate = new DateTime(year, month, day, 23, 59, 59).AddDays(-1);

                    break;

                case 2: //This week from Monday

                    DayOfWeek dayOfWeek = DateTime.Now.DayOfWeek;
                    int daysOffset = dayOfWeek - DayOfWeek.Monday;
                    DateTime start = DateTime.Now.AddDays(-daysOffset);

                    startDate = new DateTime(start.Year, start.Month, start.Day);
                    endDate = new DateTime(year, month, day, 23, 59, 59);
                    break;

                case 3: //This month
                    startDate = new DateTime(year, month, 1);
                    endDate = new DateTime(year, month, DateTime.DaysInMonth(year, month), 23, 59, 59);
                    break;

                case 4: //Custom dates
                    startDate = startDateParam;
                    endDate = endDateParam;
                    break;

                default: // Today
                    startDate = new DateTime(year, month, day);
                    endDate = new DateTime(year, month, day, 23, 59, 59);

                    break;
            }


            orders = new OrderCollection().Where("orderStatusID", SubSonic.Comparison.NotEquals, OrderStatus.NotProcessed).Where(Order.Columns.OrderDate, SubSonic.Comparison.GreaterOrEquals, startDate).Where(Order.Columns.OrderDate, SubSonic.Comparison.LessOrEquals, endDate).OrderByDesc("OrderDate").Load();

            StringBuilder csv = new StringBuilder();

            var line = new StringBuilder();

            // Header
            line.AppendFormat("\"Name\"");
            line.AppendFormat(",\"Business Name\"");
            line.AppendFormat(",\"Order Number\"");
            line.AppendFormat(",\"Order Date\"");
            line.AppendFormat(",\"Order Status\"");
            line.AppendFormat(",\"Item SKU\"");
            line.AppendFormat(",\"Item Name\"");
            line.AppendFormat(",\"Quantity\"");
            line.AppendFormat(",\"Price\"");
            line.AppendFormat(",\"Username\"");

            csv.AppendLine(line.ToString());

            // Data
            foreach (var order in orders)
            {
                OrderItemCollection orderItems =
                      new OrderItemCollection().Where(OrderItem.Columns.OrderID, SubSonic.Comparison.Equals, order.OrderID).Load();

                if (orderItems == null)
                {
                    csv.AppendLine("*** ERROR *** No item details for order #" + order.OrderNumber);
                    continue;
                }

                foreach (var orderItem in orderItems)
                {
                    var orderDetailsLine = new StringBuilder();

                    orderDetailsLine.AppendFormat("\"{0} {1}\"", order.FirstName, order.LastName);

                    // ROB: adding the business name, if available, to the order details output...
                    Member[] thisMember = Member.GetMemberByName(order.UserName, false);
                    string businessName = "";
                    if (thisMember.Length > 0)
                    {
                        if (thisMember[0].getProperty("businessName") != null)
                        {
                            businessName = thisMember[0].getProperty("businessName").Value.ToString();
                        }
                    }

                    orderDetailsLine.AppendFormat(",\"{0}\"", businessName);
                    orderDetailsLine.AppendFormat(",\"{0}\"", order.OrderNumber);
                    orderDetailsLine.AppendFormat(",\"{0}\"", order.OrderDate);
                    orderDetailsLine.AppendFormat(",\"{0}\"", order.OrderStatus);
                    orderDetailsLine.AppendFormat(",\"{0}\"", orderItem.Sku);
                    orderDetailsLine.AppendFormat(",\"{0}\"", orderItem.ProductName);
                    orderDetailsLine.AppendFormat(",\"{0}\"", orderItem.Quantity);
                    orderDetailsLine.AppendFormat(",\"{0}\"", orderItem.PricePaid);
                    orderDetailsLine.AppendFormat(",\"{0}\"", order.UserName);

                    csv.AppendLine(orderDetailsLine.ToString());
                }
            }

            string attachment = "attachment; filename=OrderDetails.csv";
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.AddHeader("content-disposition", attachment);
            HttpContext.Current.Response.ContentType = "text/csv";
            HttpContext.Current.Response.AddHeader("Pragma", "public");

            HttpContext.Current.Response.Write(csv.ToString());

            HttpContext.Current.Response.End();
        }
    }
}